package com.htandroid.htandroid.aty;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.ab.soap.AbSoapListener;
import com.ab.soap.AbSoapParams;
import com.ab.soap.AbSoapUtil;
import com.ab.util.AbToastUtil;
import com.htandroid.htandroid.R;
import com.htandroid.htandroid.sys.InstorageURL;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import static com.htandroid.htandroid.constance.ConstanceServer.BaseUrl_New;

/**
 * @author coolszy
 * @date 2012-4-26
 * @blog http://blog.92coding.com
 */

public class UpdateManager {
    /* 下载中 */
    private static final int DOWNLOAD = 1;
    /* 下载结束 */
    private static final int DOWNLOAD_FINISH = 2;
    /* 下载保存路径 */
    private String mSavePath;
    /* 记录进度条数量 */
    private int progress;
    /* 是否取消更新 */
    private boolean cancelUpdate = false;

    private Context mContext;
    /* 更新进度条 */
    private ProgressBar mProgress;
    private Dialog mDownloadDialog;
    private AbSoapUtil mAbSoapUtil = null;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // 正在下载
                case DOWNLOAD:
                    // 设置进度条位置
                    mProgress.setProgress(progress);
                    break;
                case DOWNLOAD_FINISH:
                    // 安装文件
                    installApk();
                    break;
                default:
                    break;
            }
        }
    };

    public UpdateManager(Context context) {
        this.mContext = context;
    }

    /**
     * 检查软件是否有更新版本
     *
     * @return
     */
    public void checkUpdate(TextView v) {
        // 获取当前软件版本
        mAbSoapUtil = AbSoapUtil.getInstance(mContext);
        mAbSoapUtil.setTimeout(10000);

        final Double versionname = Double.valueOf(getVersionName(mContext));
        v.setText("推动酒店管理进步 V" + versionname);
        // 通过webservice获取当前版本
//        loadingDialog.loading(mContext);
//        //设置webservice的soap参数
//        TreeMap<String, String> properties = new TreeMap<String, String>();
//        properties.put("arg0", "androidversion");
//        ToolSOAP.callService(InstorageURL.SERVERURL, InstorageURL.NAME_SPACE, "getsoftversion", properties, new ToolSOAP.WebServiceCallBack() {
//            @Override
//            public void onSucced(SoapObject result) {
//                loadingDialog.loadingfinish();
//                if (result != null) {
//                    String res = result.getProperty(0).toString();
//                    Double servicename = 0.00;
//                    if (res.equals("anyType{}") || res.equals("") || res == null) {
//                        servicename = 0.00;
//                    } else {
//                        servicename = Double.valueOf(res);
//                    }
//                    // 版本判断
//                    if (servicename > versionname) {
//                        showNoticeDialog();
//                    } else {
//                        Toast.makeText(mContext, R.string.soft_update_no, Toast.LENGTH_LONG).show();
//                    }
//                }
//            }
//
//            @Override
//            public void onFailure(String result) {
//                loadingDialog.loadingfinish();
//            }
//        });

        String urlString = "http://" + InstorageURL.SERVERURL + BaseUrl_New;
        String nameSpace = "http://service.test.com";
        String methodName = "getsoftversion";
        AbSoapParams params = new AbSoapParams();
        params.put("arg0", "androidversion");
        mAbSoapUtil.call(urlString, nameSpace, methodName, params, new AbSoapListener() {
            //获取数据成功会调用这里
            @Override
            public void onSuccess(int statusCode, String content) {
                if (content != null) {
                    String res = content.split("=")[1].split(";")[0];
                    Double servicename = 0.00;
                    if (res.equals("anyType{}") || res.equals("") || res == null) {
                        servicename = 0.00;
                    } else {
                        servicename = Double.valueOf(res);
                    }
                    // 版本判断
                    if (servicename > versionname) {
                        showNoticeDialog();
                    } else {
                        AbToastUtil.showToast(mContext, R.string.soft_update_no);
                    }
                } else {
                    AbToastUtil.showToast(mContext, R.string.sqlerrormsg);
                }
                //AbDialogUtil.removeDialog(mContext);
            }

            // 失败，调用
            @Override
            public void onFailure(int statusCode, String content,
                                  Throwable error) {
                AbToastUtil.showToast(mContext, statusCode + "====" + error.getMessage());
            }

            // 开始执行前
            @Override
            public void onStart() {
                //显示进度框
                //AbDialogUtil.showProgressDialog(context, 0, "正在加载...");
            }

            // 完成后调用，失败，成功
            @Override
            public void onFinish() {
                //移除进度框
                //AbDialogUtil.removeDialog(context);
            }
        });
    }

    /**
     * 获取软件版本号
     *
     * @param context
     * @return
     */
    private String getVersionName(Context context) {
        String versionname = "0";
        try {
            // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
            //修改build.gradle中值
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS);
            versionname = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS).versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionname;
    }

    /**
     * 显示软件更新对话框
     */
    private void showNoticeDialog() {
        // 构造对话框
        AlertDialog.Builder builder = new Builder(mContext);
        builder.setTitle(R.string.soft_update_title);
        builder.setMessage(R.string.soft_update_info);
        // 更新
        builder.setPositiveButton(R.string.soft_update_updatebtn, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                // 显示下载对话框
                showDownloadDialog();
            }
        });
        // 稍后更新
        builder.setNegativeButton(R.string.soft_update_later, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        Dialog noticeDialog = builder.create();
        noticeDialog.show();
    }

    /**
     * 显示软件下载对话框
     */
    private void showDownloadDialog() {
        // 构造软件下载对话框
        AlertDialog.Builder builder = new Builder(mContext);
        builder.setTitle(R.string.soft_updating);
        // 给下载对话框增加进度条
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.softupdate_progress, null);
        mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
        builder.setView(v);
        // 取消更新
        builder.setNegativeButton(R.string.soft_update_cancel, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                // 设置取消状态
                cancelUpdate = true;
            }
        });
        mDownloadDialog = builder.create();
        mDownloadDialog.show();
        // 现在文件
        downloadApk();
    }

    /**
     * 下载apk文件
     */
    private void downloadApk() {
        // 启动新线程下载软件
        new downloadApkThread().start();
    }

    /**
     * 下载文件线程
     *
     * @author coolszy
     * @date 2012-4-26
     * @blog http://blog.92coding.com
     */
    private class downloadApkThread extends Thread {
        @Override
        public void run() {
            try {
                // 判断SD卡是否存在，并且是否具有读写权限
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    // 获得存储卡的路径
                    String sdpath = Environment.getExternalStorageDirectory() + "/";
                    mSavePath = sdpath + "download";
                    URL url = new URL("http://" + InstorageURL.SERVERURL + "/htandroid.apk");//升级文件放在tomcat的webapp/root下
                    // 创建连接
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    // 获取文件大小
                    int length = conn.getContentLength();
                    // 创建输入流
                    InputStream is = conn.getInputStream();

                    File file = new File(mSavePath);
                    // 判断文件目录是否存在
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    File apkFile = new File(mSavePath, "htandroid");//下载的文件名称
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[1024];
                    // 写入到文件中
                    do {
                        int numread = is.read(buf);
                        count += numread;
                        // 计算进度条位置
                        progress = (int) (((float) count / length) * 100);
                        // 更新进度
                        mHandler.sendEmptyMessage(DOWNLOAD);
                        if (numread <= 0) {
                            // 下载完成
                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                            break;
                        }
                        // 写入文件
                        fos.write(buf, 0, numread);
                    } while (!cancelUpdate);// 点击取消就停止下载.
                    fos.close();
                    is.close();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 取消下载对话框显示
            mDownloadDialog.dismiss();
        }
    }

    /**
     * 安装APK文件
     */

    private void installApk() {
        File apkfile = new File(mSavePath, "htandroid");
        if (!apkfile.exists()) {
            return;
        }
        try {
            if (Build.VERSION.SDK_INT >= 24) {//判读版本是否在7.0以上
                Uri apkUri = FileProvider.getUriForFile(mContext, "com.readingparty.fileprovider", apkfile);//在AndroidManifest中的android:authorities值
                Intent install = new Intent(Intent.ACTION_VIEW);
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
                install.setDataAndType(apkUri, "application/vnd.android.package-archive");
                mContext.startActivity(install);
            } else {
                //校验MD5
                // 通过Intent安装APK文件
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
                mContext.startActivity(i);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
}
